package com.lcf.framework.interceptor;

import com.lcf.common.utils.UserUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import static com.lcf.base.constant.SysConstant.DEFAULT_TENANT_ID;
import static com.lcf.base.constant.SysConstant.SESSION_TENANT_ID_KEY;

/**
 * 描述：租户拦截器
 *
 * @author lcf
 * @since 2025/4/16 18:46
 */
@Component
public class TenantInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        String headerTenantId = request.getHeader(SESSION_TENANT_ID_KEY);
        long tenantId = StringUtils.isBlank(headerTenantId) ? DEFAULT_TENANT_ID : Long.parseLong(headerTenantId);
        UserUtils.setTenantId(tenantId);
        return true;
    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) throws Exception {
        // 清除租户 ID
        UserUtils.clearTenantId();
    }
}
